<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-shop"></i> 商品管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="goodsName" placeholder="请输入商品名称" class="handle-input mr10"></el-input>               
                <el-select v-model="query.address" placeholder="-类别-" class="handle-select mr10">
                    <el-option key="1" label="米田粮油" value="米田粮油"></el-option>
                    <el-option key="2" label="厨房调味" value="厨房调味"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-link"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量下线</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-link"
                    class="handle-del mr10"
                    @click="addAllSelection"
                >批量上线</el-button>
            </div>
                <el-table
                    :data="tableData"
                    border
                    class="table"
                    row-key="id"
                    highlight-current-row 
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                    <el-table-column prop="name" label="商品名" width="100px"></el-table-column>
                    <el-table-column label="类别" align="center">
                        <template slot-scope="scope" >￥{{scope.row.money}}</template>
                    </el-table-column>
                    <el-table-column label="供应商" align="center">
                        <template slot-scope="scope" >￥{{scope.row.money}}</template>
                    </el-table-column>
                    <el-table-column prop="address" label="来源"></el-table-column>
                    <el-table-column label="状态" align="center">
                        <template slot-scope="scope">
                            <el-tag 
                                :type="scope.row.state==='成功'?'success':(scope.row.state==='失败'?'danger':'')"
                            >{{scope.row.state}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品价格" align="center">
                        <template slot-scope="scope" >￥{{scope.row.money}}</template>
                    </el-table-column>
                    <el-table-column label="Hao呗价格" align="center">
                        <template slot-scope="scope" >￥{{scope.row.money}}</template>
                    </el-table-column>
                    <el-table-column label="优惠金额" align="center">
                        <template slot-scope="scope" >￥{{scope.row.money}}</template>
                    </el-table-column>
                    <el-table-column label="操作" width="180" align="center">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                            >编辑</el-button>
                            <el-button
                                type="text"
                                icon="el-icon-top"
                                @click="handleDelete(scope.$index, scope.row)"
                            >置顶</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="商品ID">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <!-- 上传图片 -->
                <el-form-item label="图片">
                <el-upload
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                </el-form-item>
                <el-form-item label="商品信息" label-width="100px">
                    <el-input v-model="form.address" style="width:80%" class="mr10"></el-input> <el-button type="primary">查找</el-button>
                </el-form-item>
                <el-form-item label="类别" label-width="100px">
                    <el-select v-model="query.address" placeholder="请选择" class="handle-select mr10">
                        <el-option key="1" label="厨房调味" value="厨房调味"></el-option>
                        <el-option key="2" label="米田粮油" value="米田粮油"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠券地址" label-width="100px">
                    <el-input v-model="form.address" placeholder="请输入优惠劵地址"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" label-width="100px">
                    <el-input v-model="form.money" placeholder="请输入价格"></el-input>
                </el-form-item>
                <el-form-item label="Hao呗价格" label-width="100px">
                    <el-input v-model="form.money" placeholder="请输入Hao呗价格"></el-input>
                </el-form-item>
                <el-form-item label="优惠金额" label-width="100px">
                    <el-input v-model="form.money" placeholder="请输入优惠金额"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加弹出框 -->
        <el-dialog title="添加" :visible.sync="addVisible" width="50%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="商品ID">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <!-- 上传图片 -->
                <el-form-item label="图片">
                <el-upload
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                </el-form-item>
                <el-form-item label="商品信息" label-width="100px">
                    <el-input v-model="form.address" style="width:80%" class="mr10"></el-input> <el-button type="primary">查找</el-button>
                </el-form-item>
                <el-form-item label="类别" label-width="100px">
                    <el-select v-model="query.address" placeholder="请选择" class="handle-select mr10">
                        <el-option key="1" label="厨房调味" value="厨房调味"></el-option>
                        <el-option key="2" label="米田粮油" value="米田粮油"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠券地址" label-width="100px">
                    <el-input v-model="form.address" placeholder="请输入优惠劵地址"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" label-width="100px">
                    <el-input v-model="form.money" placeholder="请输入价格"></el-input>
                </el-form-item>
                <el-form-item label="Hao呗价格" label-width="100px">
                    <el-input v-model="form.money" placeholder="请输入Hao呗价格"></el-input>
                </el-form-item>
                <el-form-item label="优惠金额" label-width="100px">
                    <el-input v-model="form.money" placeholder="请输入优惠金额"></el-input>
                </el-form-item>
            </el-form>            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import Sortable from 'sortablejs';
import { fetchData } from '../../../api/index';

export default {
    name: 'basetable',
    data() {
        return {

            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            ElDate:'',//日期的变量
            value: '',
            value2: '',
            goodsName:'',//搜索框商品名称
            imageUrl: ''//上传图片的变量
        };
    },
    created() {
        this.getData();
    },
    mounted(){
    this.setSort();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            fetchData(this.query).then(res => {
                console.log(res);
                this.tableData = res.list;
                this.pageTotal = res.pageTotal || 50;
            });
        },
        /**
         * 排序方法
         */
        setSort(){
        const el = this.$refs.multipleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
        this.sortable = Sortable.create(el,{
            ghostClass:'sortable-ghost',
            setData:function(dataTransfer){
            dataTransfer.setData('Text', '')
            },
            onEnd: evt => {
            const targetRow = this.tableData.splice(evt.oldIndex, 1)[0];
            this.tableData.splice(evt.newIndex, 0, targetRow);
            }   
        })
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`下线了${str}`);
            this.multipleSelection = [];
        },
        //批量上线
        addAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.success(`上线了${str}`);
            this.multipleSelection = [];
        },

        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
            console.log(index,row,'111')
        },
        //添加操作
        handleAdd(){
            this.addVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        //上传图片有关函数
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 130px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
.el-upload--text {
    width: 180px;
  }
</style>
